package com.bookyourtrek.action;

import java.io.File;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.bookyourtrek.model.ImageModel;
import com.bookyourtrek.model.TicketModel;
import com.bookyourtrek.model.TrekModel;
import com.bookyourtrek.util.RuntimeSettings;
import com.bookyourtrek.util.UtilityFunctions;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UpdateTrekAction extends ActionSupport implements ServletRequestAware{

	private BigInteger ticketid;
	private BigInteger trekkingid;
	private String trektitle;
	private String location;
	private String locationdetail;
	private String date;
	private String gender;
	private String duration;
	private String distance;
	private String difficultylevel;
	private String trekplan;
	private List<String> gears;
	private String organizationname;
	private String organizationphone;
	private String status;
	
	//tkt related 
	private String tkttype;
	private Integer tktquantity;
	private String tktamount;
	private String tktenddate;
	private String tktdescription;
	private Integer tktallowedperorder;
	
	//image related
	private List<File> fileUpload = new ArrayList<File>();
	private List<String> fileUploadContentType = new ArrayList<String>();
	private List<String> fileUploadFileName = new ArrayList<String>();
	private ArrayList<String> tmppics = new ArrayList<String>();
	
	
	public BigInteger getTicketid() {
		return ticketid;
	}

	public void setTicketid(BigInteger ticketid) {
		this.ticketid = ticketid;
	}

	public BigInteger getTrekkingid() {
		return trekkingid;
	}

	public void setTrekkingid(BigInteger trekkingid) {
		this.trekkingid = trekkingid;
	}

	public ArrayList<String> getTmppics() {
		return tmppics;
	}

	public void setTmppics(ArrayList<String> tmppics) {
		this.tmppics = tmppics;
	}

	private HttpServletRequest servletRequest;
	
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}

	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}

	public List<File> getFileUpload() {
		return fileUpload;
	}

	public void setFileUpload(List<File> fileUpload) {
		this.fileUpload = fileUpload;
	}

	public List<String> getFileUploadContentType() {
		return fileUploadContentType;
	}

	public void setFileUploadContentType(List<String> fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}

	public List<String> getFileUploadFileName() {
		return fileUploadFileName;
	}

	public void setFileUploadFileName(List<String> fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}

	public String getTkttype() {
		return tkttype;
	}

	public void setTkttype(String tkttype) {
		this.tkttype = tkttype;
	}

	public Integer getTktquantity() {
		return tktquantity;
	}

	public void setTktquantity(Integer tktquantity) {
		this.tktquantity = tktquantity;
	}

	public String getTktamount() {
		return tktamount;
	}

	public void setTktamount(String tktamount) {
		this.tktamount = tktamount;
	}

	public String getTktenddate() {
		return tktenddate;
	}

	public void setTktenddate(String tktenddate) {
		this.tktenddate = tktenddate;
	}

	public String getTktdescription() {
		return tktdescription;
	}

	public void setTktdescription(String tktdescription) {
		this.tktdescription = tktdescription;
	}

	public Integer getTktallowedperorder() {
		return tktallowedperorder;
	}

	public void setTktallowedperorder(Integer tktallowedperorder) {
		this.tktallowedperorder = tktallowedperorder;
	}

	public String getTrektitle() {
		return trektitle;
	}

	public void setTrektitle(String trektitle) {
		this.trektitle = trektitle;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getLocationdetail() {
		return locationdetail;
	}

	public void setLocationdetail(String locationdetail) {
		this.locationdetail = locationdetail;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getDuration() {
		return duration;
	}

	public void setDuration(String duration) {
		this.duration = duration;
	}

	public String getDistance() {
		return distance;
	}

	public void setDistance(String distance) {
		this.distance = distance;
	}

	public String getDifficultylevel() {
		return difficultylevel;
	}

	public void setDifficultylevel(String difficultylevel) {
		this.difficultylevel = difficultylevel;
	}

	public String getTrekplan() {
		return trekplan;
	}

	public void setTrekplan(String trekplan) {
		this.trekplan = trekplan;
	}


	public List<String> getGears() {
		return gears;
	}

	public void setGears(List<String> gears) {
		this.gears = gears;
	}

	public String getOrganizationname() {
		return organizationname;
	}

	public void setOrganizationname(String organizationname) {
		this.organizationname = organizationname;
	}

	public String getOrganizationphone() {
		return organizationphone;
	}

	public void setOrganizationphone(String organizationphone) {
		this.organizationphone = organizationphone;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * updatetrek trek event
	 * @author ananda
	 * @return
	 * @throws ParseException 
	 */
	@SuppressWarnings({ "rawtypes" })
	public String updatetrek() throws ParseException {
		//validation
		//title validation starts here
		if(trektitle == null || trektitle.equalsIgnoreCase("")) {
			addFieldError("trektitle", "Title required");
			return INPUT;
		}
		if(trektitle.length() < 6) {
			addFieldError("trektitle", "Title should be more than 6 characters");
			return INPUT;		
		}
		//title validation ends here
		
		//trek plan validation starts here
		//trek plan validation ends here
		
		//trek location validation starts here
		//trek location validation ends here
		
		//trek location details validation starts here
		//trek location details validation ends here
		
		//trek Date validation starts here
		
		
		if(date == null || date.equalsIgnoreCase("")) {
			addFieldError("trekdate", "Date required");
			return INPUT;
		}
		
		//trek Date validation ends here
		
		//trek duration validation starts here
		if(duration == null || duration.equalsIgnoreCase("")) {
			addFieldError("trekduration", "Duration required");
			return INPUT;
		}
		if(Integer.parseInt(duration) < 0) {
			addFieldError("trekduartion", "Duration can not be less than 0 days");
			return INPUT;
		}
		if(Integer.parseInt(duration) > 31) {
			addFieldError("trekduartion", "Duration can not be more than 31 days");
			return INPUT;
		}
		//trek duration validation ends here
		
		//trek gender validation starts here
		//System.out.println(gender);
		//trek gender validation ends here
		
		//Trek distance validation starts here
		if(distance == null || distance.equalsIgnoreCase("")) {
			addFieldError("trekdistance", "Distance required");
			return INPUT;
		}
		if(Integer.parseInt(distance) < 0) {
			addFieldError("trekdistance", "Distance can not be less than 0 Kms");
			return INPUT;
		}
		//Trek distance validation ends here
		
		//Trek difficulty level validation starts here
		//Trek difficulty level validation ends here
		
		//Trek Gear required validation starts here
		//Trek Gear required validation ends here
		
		//Trek organization name validation starts here
		if(organizationname == null || organizationname.equalsIgnoreCase("")) {
			addFieldError("organizationname", "Organization name required");
			return INPUT;
		}
		if(organizationname.length() < 3) {
			addFieldError("organizationname", "Organization name can not be less than 3 characters");
			return INPUT;
		}
		//Trek organization name ends here
		
		//Trek organization phone validation starts here
		if(organizationphone == null || organizationphone.equalsIgnoreCase("")) {
			addFieldError("organizationphone", "Organization mobile no. required");
			return INPUT;
		}
		if(organizationphone.length() < 10) {
			addFieldError("organizationphone", "Organization mobile can not be less than 10 digits");
			return INPUT;
		}		
		//Trek organization phone validation ends here
		
		//tkt type validation starts here
		//tkt type validation ends here
		
		//tkt quantity validation starts here
		if( tktquantity == null || tktquantity.toString().equalsIgnoreCase("")) {
			addFieldError("tktquantity", "Ticket quantity required");
			return INPUT;
		}
		if( tktquantity < 1) {
			addFieldError("tktquantity", "Ticket quantity can not be less than 1");
			return INPUT;
		}
		//tkt quantity validation ends here
		
		//tkt amount validation starts here
		
		if(tkttype.equalsIgnoreCase(RuntimeSettings.TKTPAID) || tkttype.equalsIgnoreCase(RuntimeSettings.TKTSOCIAL)) {
			if( tktamount == null || tktamount.toString().equalsIgnoreCase("")) {
				addFieldError("tktamount", "Ticket amount required");
				return INPUT;
			}
			if(!UtilityFunctions.isNumeric(tktamount)) {
				addFieldError("tktamount", "Ticket amount invalid");
				return INPUT;
			}
			if( Double.parseDouble(tktamount) < 0.0) {
				addFieldError("tktamount", "Ticket amount can not be less than Rs. 0.0");
				return INPUT;
			}
		}
		if( tktamount == null || tktamount.toString().equalsIgnoreCase("")) {
			tktamount = "0.0";
		}
		//tkt amount validation ends here
		
		//tkt Date validation starts here
		if(tktenddate == null || tktenddate.equalsIgnoreCase("")) {
			addFieldError("tktenddate", "Ticket End date required");
			return INPUT;
		}
		DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-mm-yy");
		//System.out.println(Days.daysBetween(new DateTime(formatter.parseDateTime(date)), new DateTime(formatter.parseDateTime(tktenddate))).getDays());
		if(Days.daysBetween(new DateTime(formatter.parseDateTime(tktenddate)), new DateTime(formatter.parseDateTime(date))).getDays() < 1){
			addFieldError("tktenddate", "Ticket end date must be before trek start date");
			return INPUT;
		}
		//tkt Date validation ends here
		
		//tkt allowed per order validation starts here
		if(tktallowedperorder == null || tktallowedperorder.toString().equalsIgnoreCase("")) {
			tktallowedperorder = -1;
		}
		if(tktallowedperorder != -1) {
			if(tktallowedperorder > tktquantity) {
				addFieldError("tktallowedperorder", "Ticket allowed per order can not be more than ticket quntity");
				return INPUT;
			}
		}
		//tkt allowed per order validation ends here
		//validation ends here
		
		//image processing starts here
		try {
			
			//get path to upload photo
			/*ServletContext servletContext = servletRequest.getSession().getServletContext();
			String relativeWebPath = "/uploads/pictures";
			String filePath = servletContext.getRealPath(relativeWebPath);*/
            String filePath = servletRequest.getSession().
            		getServletContext().getRealPath("/uploads/pictures");
            
		//debugging
	    for (int i=0; i < fileUpload.size(); i++) {
	        System.out.println("File :" + fileUpload.get(i));
	      //creating unique picture name
        	Map sess = (Map) ActionContext.getContext().get("session");
    		BigInteger uid = (BigInteger) sess.get("userid");
        	String photoName = uid + "-" + 
        			UtilityFunctions.createRandomUrl() + "-" + fileUploadFileName.get(i);
        	
        	//photo url	
        	String photoUrl = "uploads/pictures/" + photoName;        	
        	
        	//create new File with new path and name
            File fileToCreate = new File(filePath, photoName);
            
            //copy file to given location and with given name
            FileUtils.copyFile(fileUpload.get(i), fileToCreate);  
            
            tmppics.add(photoUrl);
	    } 
	    }catch (Exception e) {
            e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;
        }
		//image processing ends here
		
		
		
		//update db entry for trek
		TrekModel trekmodel = new TrekModel();
		Map sess=ActionContext.getContext().getSession();
		BigInteger userid = (BigInteger) sess.get("userid");
		//System.out.println(userid);
		trekmodel.updatetrek(trektitle, location, locationdetail, date, gender, 
				duration, distance, difficultylevel, trekplan, gears, 
				organizationname, organizationphone, userid, RuntimeSettings.ADVENTURESTATUSSAVE.toString(), trekkingid );
		
		//db entry for images
		ImageModel imgmodel = new ImageModel();
		for(int i=0; i<tmppics.size(); i++) {
			imgmodel.insertimage(trekkingid, tmppics.get(i));
		}
		
		//update db entry for tkt
		TicketModel tktmodel = new TicketModel();
		tktmodel.updatetkt(trekkingid, RuntimeSettings.EVENTTREKKING.toString(), tkttype, tktamount, 
				tktquantity, tktdescription, tktenddate, tktallowedperorder, ticketid);
		
		return SUCCESS;
	}

}
